package com.auth.service.impl;

import com.auth.entity.dao.UserRole;
import com.auth.entity.dto.RoleDto;
import com.auth.mapper.UserRoleMapper;
import com.auth.service.IRoleService;
import com.auth.service.IUserRoleService;
import com.auth.util.MybaitsUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.auth.entity.factory.RoleFactory.ROLE_CONVERTER;

@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {
    @Autowired
    private IRoleService iRoleService;

    @Override
    public void delByUserId(Integer id) {
        remove(new QueryWrapper<UserRole>().eq("uid",id));
    }

    @Override
    public void removeByRoleId(Integer id) {
        remove(new QueryWrapper<UserRole>().eq("rid",id));
    }

    @Override
    public List<RoleDto> getRoleOfUser(Integer userId) {
        List<Integer> rIdList = listByMap(Map.of("uid", userId)).stream().map(UserRole::getRid).collect(Collectors.toList());
        return ObjectUtils.isEmpty(rIdList)?null:ROLE_CONVERTER.toListRoleDto(iRoleService.listByIds(rIdList));
    }

    @Transactional
    @Override
    public void releaseRoleToUser(Integer userId, List<Integer> roleIdList) {
        if (roleIdList == null) {
            return;
        }
        //跳过已经赋予的权限
        for (Integer id : roleIdList) {
            if (!MybaitsUtils.existCheck(this, Map.of("rid", id, "uid", userId))) {
                save(UserRole.builder().rid(id).uid(userId).build());
            }
        }
    }

    @Transactional
    @Override
    public void revokeRoleFromUser(Integer userId, List<Integer> roleIdList) {
        if (roleIdList == null) {
            return;
        }
        for (Integer id : roleIdList) {
            remove(new QueryWrapper<UserRole>().eq("rid", id).eq("uid", userId));
        }
        ;
    }
}
